package com.apes.framework.query.lib;

import com.apestech.api.condition.ConditionExec;
import com.apestech.api.xml.esb.EsbUtil;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.db.callback.TableJsonCallBackHandler;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.util.DateUtil;
import com.apestech.framework.util.LocalVariable;
import com.apestech.framework.util.StringUtil;
import com.apestech.framework.xml.plugin.modul.SysCondition;

import java.util.ArrayList;
import java.util.Date;

public class JPAConditionQuery extends StringUtil implements TableJsonCallBackHandler{
    private JSONObject json;
    private ConditionExec exec;
    private SysCondition sysCondition;
    private SqlSession session;

    public JPAConditionQuery(JSONObject json, ConditionExec exec, SqlSession session) throws Exception {
        this.json=json;
        this.exec=exec;
        this.session=session;
        sysCondition=LocalVariable.getConfig().getSysCondition(session);
    }

    @Override
    public JSONObject getJSON(String tableName, JSONObject data) throws Exception {
        JSONObject isFieldmap= (JSONObject) json.get("SYS_IS_FIELD");
        String isField=null;
        if(isFieldmap!=null){
            isField=isFieldmap.getString(tableName);
        }
        data=EsbUtil.getConData(data, session, sysCondition);
        if(tableName.equals(json.getString("sysTable"))){
            JSONObject j=new JSONObject();
            j.put("ID", json.getString("CID"));
            j.put("NAME", json.getString("CNAME"));
            data.put("EXE_CONDITION", j);
            j=new JSONObject();
            j.put("ID", json.getString("MID"));
            j.put("NAME", json.getString("MNAME"));
            data.put("EXE_DIMENSION", j);
            data.put("START_DATE", DateUtil.dateTimeToStr(data.getDate("START_DATE")));
            data.put("END_DATE", DateUtil.dateTimeToStr(data.getDate("END_DATE")));
            data.put("LAST_UPDATED_STAMP", DateUtil.getTimeStampStr(data.getDate("LAST_UPDATED_STAMP")));
        }
        return data;
    }

    @Override
    public JSONObject getSubTable(String tableName, JSONObject data) throws Exception {
        if(tableName.equals(json.getString("sysTable"))){
            data.put("ITEMS", data.get(tableName+"_ITEM"));
            data.remove(tableName+"_ITEM");
        }
        return data;
    }
}
